const express = require('express')
const {
    v4: uuidv4
} = require('uuid')
const session = require('express-session')
const RedisStore = require('./redis')(session)
const config = require('./config')

let app = express()

app.use(session({
    name: "session",
    secret: "session_@@key",
    genid: uuidv4,
    store: new RedisStore({
        client: config.RedisServer,
        prefix: 'userSession:'
    }),
    resave: false,
    rolling: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 15 * 60 * 1000 //Session有效期
    }
}));

app.get('/', (req, res) => {
    console.log(req.sessionID)
    if (req.session.views) {
        req.session.views++
        res.setHeader('Content-Type', 'text/html')
        res.send(`<p>views: ${req.session.views}</p><p>expires in: ${req.session.cookie.maxAge / 1000}s</p>`)
    } else {
        req.session.views = 1
        res.send('welcome to the session demo. refresh!')
    }
})


app.listen(9090, () => {
    console.log('server running at 9090.')
})